package com.hao.wms.service.impl;

import com.hao.wms.dao.IProductStockDao;
import com.hao.wms.domain.Depot;
import com.hao.wms.domain.Product;
import com.hao.wms.domain.ProductStock;
import com.hao.wms.query.PageResult;
import com.hao.wms.query.QueryObject;
import com.hao.wms.service.IProductStockService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

public class ProductStockServiceImpl implements IProductStockService {
	private IProductStockDao dao;
	

	public void setDao(IProductStockDao dao) {
		this.dao = dao;
	}

	@Override
	public void save(ProductStock productStock) {
		dao.save(productStock);

	}

	@Override
	public void update(ProductStock productStock) {
		dao.update(productStock);

	}

	@Override
	public void delete(ProductStock productStock) {
		dao.delete(productStock);

	}

	@Override
	public ProductStock get(Long id) {
		return dao.get(id);
	}

	@Override
	public List<ProductStock> list() {
		return dao.list();
	}

	@Override
	public PageResult query(QueryObject qo) {
		return dao.query(qo);
	}

	@Override
	public void income(Depot depot, Product product, BigDecimal number, BigDecimal costPrice) {
		ProductStock ps = dao.getByDepotAndProduct(depot.getId(),product.getId());
		BigDecimal amount = costPrice.multiply(number).setScale(2, RoundingMode.HALF_UP);
		if(ps!=null){
			ps.setStoreNumber(ps.getStoreNumber().add(number));
			ps.setAmount(ps.getAmount().add(amount));
			ps.setPrice(ps.getAmount().divide(ps.getStoreNumber(),2,RoundingMode.HALF_UP));
			dao.update(ps);
		}else {
			ps = new ProductStock();
			ps.setPrice(costPrice);
			ps.setStoreNumber(number);
			ps.setProduct(product);
			ps.setAmount(amount);
			ps.setDepot(depot);
			dao.save(ps);
		}
	}

	@Override
	public void outcome(Depot depot, Product product, BigDecimal number) {
		ProductStock ps = dao.getByDepotAndProduct(depot.getId(),product.getId());
		if(ps==null||ps.getStoreNumber().compareTo(number)<0){
			throw new RuntimeException(product.getName()+"数量不足"+number);
		}
		ps.setStoreNumber(ps.getStoreNumber().subtract(number));
		ps.setAmount(ps.getPrice().multiply(ps.getStoreNumber()));
		dao.update(ps);
	}
}
